package com.kingschan.jeasytag.tag.head;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.kingschan.jeasytag.tag.EasyTag;
/**
 * 
 * @author kingschan
 * <pre>
 * date:2012-12-13
 * description:easyui support javascript file import
 * version:1.0
 * </pre>
 */
public class EasyTagHead extends BodyTagSupport {
	private static final long serialVersionUID = 1L;
	private String skin;	
	@Override
	public int doEndTag() throws JspException {
		JspWriter out = this.pageContext.getOut();
		HttpServletRequest request=(HttpServletRequest) this.pageContext.getRequest();
		String path=request.getContextPath();		
		StringBuffer htmlstr = new StringBuffer();	
		htmlstr.append("<link id=\"jeasytag-skin\" rel=\"stylesheet\" type=\"text/css\" href=\""+path+"/jeasytag_resource/easyui/themes/"+this.skin+"/easyui.css\">\n");
		htmlstr.append(SupportResources.getResources(EasyTagHead.class));
		EasyTag easytag = (EasyTag) pageContext.getAttribute("easytag");
		if (null!=easytag&&null!=easytag.getSupport()) {
			Iterator<?> itera = easytag.getSupport().iterator();
			while (itera.hasNext()) {
				Class<?> key = (Class<?>) itera.next();
				htmlstr.append(SupportResources.getResources(key));
				
			}
		}
		if (null!=easytag) {
			if (easytag.getDEFINE_SCRIPT().toString().length()>0||easytag.getONLOAD_SCRIPT().toString().length()>0) {
				htmlstr.append("<script type=\"text/javascript\">\n");
				htmlstr.append(easytag.getDEFINE_SCRIPT().toString());
				if (easytag.getONLOAD_SCRIPT().toString().length() > 0) {
					htmlstr.append(" window.onload=function(){\n");					
					htmlstr.append(easytag.getONLOAD_SCRIPT().toString());
					htmlstr.append(" \n}\n");
				}
				htmlstr.append("</script>\n");
			}
		}
		
		try {
			out.println(htmlstr);
		} catch (IOException e) {			
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	public String getSkin() {
		return skin;
	}

	public void setSkin(String skin) {
		this.skin = skin;
	}
	
}
